package com.chenwc;

import com.chenwc.cos.CosUtils;
import com.chenwc.fileUtils.ReadFile;
import com.chenwc.fileUtils.WriteFile;
import com.chenwc.httputil.RestMock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chenwc
 */
public class Main {

    private static final Logger log = LoggerFactory.getLogger(Main.class);

    private static final File FILESSSS = new File("1.txt");
    /**
     * 本地文件保存路径
     */
    private static final String SAVE_FILE_PATH = FILESSSS.getAbsolutePath().replace("1.txt", "") + "saveFile\\";

    /**
     * 正则表达式，匹配markdown里面所有的图片url
     */
    private static final String MARKDOWN_IMAGE_PATTERN = "!\\[(.*?)\\]\\((.*?)\\)";

    public static void main(String[] args) {

        //获取文件夹里面所有的文件
        File fileDir = new File("D:\\Downloads\\123456");
        File[] files = fileDir.listFiles();
        if (null == files || files.length == 0){
            log.info("目录: {} 下面没有任何文件！", fileDir.getAbsoluteFile());
            return;
        }

        CosUtils.setCosClient("", "", "ap-guangzhou");
        String bucketName = "calvinchan-1308961508";
        String path = "data/image";
        int yearInt = LocalDate.now().getYear();
        int monthInt = LocalDate.now().getMonthValue();
        int dayInt = LocalDate.now().getDayOfMonth();
        String year = String.valueOf(yearInt);
        String month = monthInt < 10 ? "0" + monthInt : String.valueOf(monthInt);
        String day = dayInt < 10 ? "0" + dayInt : String.valueOf(dayInt);
        //cos存储路径是年/月/日
        path = path + "/" + year + "/" + month + "/" + day;

        for(File file : files){
            log.info("file: {}", file.getAbsolutePath());
            //读文件
            String content = ReadFile.readFileByInputStreamReader(file.getAbsolutePath());
            log.debug("fileContent: {}", content);
            //获取文件url
            Set<String> imgSet = getMdImgUrl(content);
            log.debug("imgSet: {}", imgSet);

            //逐个图片上传到cos
            for (String urlImg : imgSet) {
                String localFilePath = SAVE_FILE_PATH + UUID.randomUUID().toString().replace("-", "") + ".png";
                log.info("localFilePath: {}", localFilePath);
                //把图片下载到本地
                if (RestMock.downloadFileByGet(urlImg, localFilePath)) {
                    File localSaveFile = new File(localFilePath);
                    String key = path + "/" + localSaveFile.getName();
                    //上传图片到cos
                    if (!CosUtils.isExistObject(bucketName, key)) {
                        CosUtils.uploadObject(bucketName, key, localSaveFile);
                    }
                    String cosUrl = CosUtils.getObjectUrl(bucketName, key);
                    log.info("URL: {}", cosUrl);
                    //替换markdown文件里面的url为cos的url
                    content = content.replace(urlImg, cosUrl);
                }
            }
            //把替换后的文件内容写入回文件
            WriteFile.writeFileByWriter(content, file.getAbsolutePath());
        }

        // 关闭客户端(关闭后台线程)
        CosUtils.closeCosClient();
    }

    /**
     * 通过正则把文件里面所有的图片url匹配出来
     * @param mdStr 文件内容
     * @return 图片url列表
     */
    public static Set<String> getMdImgUrl(String mdStr){
        Set<String> imgSet = new HashSet<>();
        Pattern pattern = Pattern.compile(MARKDOWN_IMAGE_PATTERN, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(mdStr);

        while(matcher.find()){
            String imgUrl = matcher.group(2);
            imgSet.add(imgUrl);
        }
        return imgSet;
    }
}
